package br.usp.ime.origami.main;

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Scanner;

import javax.swing.JFrame;

import br.usp.ime.origami.algorithms.Triangulation;
import br.usp.ime.origami.model.MovingPoint;
import br.usp.ime.origami.model.MovingTriangle;
import br.usp.ime.origami.model.MovingTriangulation;
import br.usp.ime.origami.model.SimplePoint;
import br.usp.ime.origami.model.SimplePolygon;
import br.usp.ime.origami.util.PolygonReader;
import br.usp.ime.origami.view.Drawer;

public class TestEvents implements KeyListener, MouseListener {
	public static void main(String[] args) throws FileNotFoundException {
		new TestEvents().run();
	}

	private MovingTriangulation movingTriangulation;

	private Drawer drawer;

	private int event = -1;

	private void run() throws FileNotFoundException {
		JFrame frame = new JFrame();
		this.drawer = new Drawer();
		frame.addMouseListener(this);
		drawer.addMouseListener(this);

		frame.add(drawer);
		frame.setSize(800, 600);
		frame.setVisible(true);

		SimplePolygon p = PolygonReader.getPolygon(new FileInputStream(
				"polygons\\aichholzer2.polygon"));
		List<MovingTriangle> triangles = new Triangulation(p).getTriangles();
		this.movingTriangulation = new MovingTriangulation(triangles);
		draw(0);

	}

	public void keyTyped(KeyEvent e) {
	}

	public void keyPressed(KeyEvent e) {
		// TODO Auto-generated method stub

	}

	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub

	}

	public void mouseClicked(MouseEvent e) {
		if (e.getButton() == MouseEvent.BUTTON1) {
			this.draw(1);
		} else {
			this.draw(-1);
		}
	}

	private void draw(int increment) {
		drawer.clear();

		List<MovingTriangle> triangles = movingTriangulation
				.getMovingTriangles();

		double time = 0;

		if (event >= 0 && event < triangles.size()) {
			time = triangles.get(event).getCollapsingTime();
		}

		for (int i = 0; i < movingTriangulation.getMovingTriangles().size(); i++) {
			MovingTriangle t = triangles.get(i);
			//drawer.addTriangle(t.getPositionAt(0), Color.RED);

			if (i > this.event) {
				drawer.addTriangle(t.getPositionAt(time), Color.BLUE);
			}
			if (i == this.event + 1) {
				drawer.addFilledTriangle(t.getPositionAt(time), Color.BLACK);
			}
            System.out.println(this.event);
            
		}

		drawer.repaint();

		this.event += increment;
	}

	public void mousePressed(MouseEvent e) {

	}

	public void mouseReleased(MouseEvent e) {

	}

	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub

	}

}
